package com.zz.log;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class GiftDistribution {
    private static final int TOTAL_GIFTS = 100;
    private static final int STOP_THRESHOLD = 10;
    private static final Map<String, AtomicInteger> giftCountMap = new HashMap<>();
    private static AtomicInteger remainingGifts = new AtomicInteger(TOTAL_GIFTS);

    static {
        giftCountMap.put("小明", new AtomicInteger(0));
        giftCountMap.put("小红", new AtomicInteger(0));
    }

    public static void main(String[] args) {
        Thread mingThread = new Thread(new GiftSender("小明"));
        Thread hongThread = new Thread(new GiftSender("小红"));

        mingThread.start();
        hongThread.start();

        try {
            mingThread.join();
            hongThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("剩余礼物数量: " + remainingGifts.get());
        System.out.println("小明送出的礼物数量: " + giftCountMap.get("小明").get());
        System.out.println("小红送出的礼物数量: " + giftCountMap.get("小红").get());
    }

    static class GiftSender implements Runnable {
        private final String name;

        public GiftSender(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            while (remainingGifts.get() >= STOP_THRESHOLD) {
                if (remainingGifts.decrementAndGet() >= 0) {
                    giftCountMap.get(name).incrementAndGet();
                    System.out.println(Thread.currentThread().getName() + "送出了一份礼物，剩余礼物数量：" + remainingGifts.get());
                }
            }
        }
    }
}